package org.tong.activiti6.test.commons;

import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.impl.history.HistoryManager;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;

import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * @author
 * @date 2022-07-27 22:47
 */
public class JumpAnyWhereCmd implements Command {

    private String taskId;

    private String targetNodeId;

    public JumpAnyWhereCmd(String taskId, String targetNodeId) {
        this.taskId = taskId;
        this.targetNodeId = targetNodeId;
    }

    @Override
    public Object execute(CommandContext commandContext) {
        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
        //当前任务
        TaskEntity currentTask = taskEntityManager.findById(taskId);
        // 执行实例
        ExecutionEntity execution = currentTask.getExecution();
        // 流程定义
        String processDefinitionId = execution.getProcessDefinitionId();
        // 流程
        Process process = ProcessDefinitionUtil.getProcess(processDefinitionId);
        // 获取目标节点
        FlowElement flowElement = process.getFlowElement(targetNodeId);
        if (flowElement instanceof Task) {// 任务节点
            Task targetTask = (Task) flowElement;
            List<SequenceFlow> outgoingFlows = targetTask.getOutgoingFlows();
            outgoingFlows.forEach(sequenceFlow -> {
                sequenceFlow.getTargetFlowElement();
            });

        } else if (flowElement instanceof EndEvent) {// 结束节点
            Event targetEvent = (Event) flowElement;

        }

        // 清理当前节点
        HistoryManager historyManager = commandContext.getHistoryManager();
        historyManager.recordActivityEnd(execution, "jump to " + targetNodeId);
        historyManager.recordTaskEnd(taskId, "jump to " + targetNodeId);
        taskEntityManager.delete(taskId);
        // 设置目标节点为当前活动节点
        execution.setCurrentFlowElement(flowElement);
        commandContext.getAgenda().planContinueProcessOperation(execution);
        return null;
    }
}
